package com.jj.thrift.client;

import com.jj.ftg.BattleCalculate;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Data
@Slf4j
@Component
public class VerifyClient {
    @Value("${verify.host:192.168.12.140}")
    private String host = "192.168.12.140";

    @Value("${verify.port:9090}")
    private int port = 9090;

    private TTransport transport = null;
    private BattleCalculate.Client client = null;
    private BattleCalculate.AsyncClient asyncClient = null;
    private ThriftWorker thriftWorker;

    @PostConstruct
    public void init(){
        thriftWorker = new ThriftWorker();
        thriftWorker.start();
    }

    public BattleCalculate.Client getClient(){
        return client;
    }

    public BattleCalculate.AsyncClient getAsynClient(){
        return asyncClient;
    }

//    public static void main(String[] args) throws TException {
//        TTransport transport = new TSocket(host, port);
//        transport.open();
//
//        TProtocol protocol = new TBinaryProtocol(transport);
//        BattleCalculate.Client client = new BattleCalculate.Client(protocol);
//
//        ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer();
//        buf.writeBytes("hello from java client  zzzzzzz".getBytes());
//        String retMsg = client.calc(buf.nioBuffer());
//        log.debug("ret:{}", retMsg);
//
//        transport.close();
//    }


    private class ThriftWorker extends Thread{
        {
            setDaemon(true);
        }
        @Override
        public void run() {
            log.debug("ThriftWorker is running!");
            while(true){
                transport = new TSocket(host, port);
                TProtocol protocol = new TBinaryProtocol(transport);
                try{
                    transport.open();
                }catch (Throwable t){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                client = new BattleCalculate.Client(protocol);

                while(transport.isOpen()){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
